package com.kg.alarmclock.utils

import android.annotation.SuppressLint
import android.content.Context
import com.kg.alarmclock.Constant
import com.kg.alarmclock.model.AlarmClockEntity
import java.io.*

class DataUtils {

    companion object {
        @SuppressLint("StaticFieldLeak")
        var context: Context? = null
        var fileName = ""

        fun init(context: Context) {
            this.context = context
            fileName =
                Companion.context!!.getExternalFilesDir(null).toString()

            var file = File(fileName)
            if (!file.exists())
                file.mkdirs()
        }

        fun save(entities: List<AlarmClockEntity>) {
            var file = File(fileName + File.separator + Constant.CACHE_PATH)

            try {
                var outputStream = ObjectOutputStream(FileOutputStream(file))
                outputStream.writeObject(entities)
                outputStream.flush()
                outputStream.close()
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }

        fun getList(): List<AlarmClockEntity> {
            var file = File(fileName + File.separator + Constant.CACHE_PATH)
            var entities = ArrayList<AlarmClockEntity>()

            if (!file.exists())
                file.createNewFile()

            try {
                var inputStream = ObjectInputStream(FileInputStream(file))
                var alarmClockEntities = inputStream.readObject() as ArrayList<AlarmClockEntity>

                for (alarmClockEntity in alarmClockEntities) {
                    entities.add(alarmClockEntity)
                }

                inputStream.close()
            } catch (e: Exception) {
                e.printStackTrace()
                return entities
            }
            return entities
        }
    }
}